<?php
class template
{

    public $tpl_default_dir = NULL;
    public $tpl_refresh_time = NULL;

    public function tpl($file)
    {
        $tplfile=$this->tpl_default_dir."/".$file.".htm";
        $compiledtpldir=$this->tpl_default_dir.".tpl";
        $compiledtplfile=$compiledtpldir."/".$file.".tpl.php";
        if (!is_dir($compiledtpldir))
        {
            mkdir($compiledtpldir, 511);
        }
        if (!file_exists($compiledtplfile)&&time( )-@filemtime($tplfile)<$this->tpl_refresh_time)
        {
            $this->tpl_compile($tplfile,$compiledtplfile);
        }
        clearstatcache( );
        return $compiledtplfile;
    }

    public function tpl_compile($tplfile,$compiledtplfile)
    {
        $str=$this->tpl_read($tplfile);
        $str=$this->tpl_parse($str);
        if ( $this->tpl_write($compiledtplfile, $str))
        {
            return true;
        }
        return false;
    }

    public function tpl_parse($str)
    {
        $str=str_replace( "{typeplayer}", "<?=typeplayer(\$tun2array[0][\"urltype\"])?>\n",$str);
        $str=preg_replace( "/([\n\r]+)\t+/s", "\\1",$str);
        $str=preg_replace( "/\\{template\\s+(.+)\\}/", "<?php include template(\\1); ?>\n",$str);
        $str=preg_replace( "/\\{loop\\}/", "<? if(is_array(\$tun2array)) for(\$i=0; \$i<count(\$tun2array); \$i++) { ?>",$str);
        $str=preg_replace( "/\\{\\/loop\\}/", "\n<? } ?>\n",$str);
        $str=preg_replace( "/{(\\\$[a-zA-Z_-][a-zA-Z0-9_-]*)\\}/", "<?=\\1?>",$str);
        $str=preg_replace( "/{(\\\$[a-zA-Z0-9_\\[\\]\\'\"\$-]+)\\}/s", "<?=\\1?>",$str);
        $str=preg_replace( "/\\{(flash\\((.*)\\))\\}/", "<?=\\1?>",$str);
        $str=preg_replace( "/\\{(showpage\\((.*)\\))\\}/", "<?=\\1?>",$str);
        $str=preg_replace( "/\\{([a-zA-Z_-][a-zA-Z0-9_-]*\\((.*)\\))\\}/", "<? \$tun2array=\\1?>",$str);
        $str=preg_replace( "/\\{([a-zA-Z_-][a-zA-Z0-9_-]*)\\[(\\S+)\\]\\}/", "<?=cnsubstr(\$tun2array[\$i][\"\\1\"],\\2)?>", $str );
        $str=preg_replace( "/\\{([a-zA-Z_-][a-zA-Z0-9_-]*)\\}/s", "<?=\$tun2array[\$i][\"\\1\"]?>",$str);
        $str="<? if(!defined('IN')) exit('Access Denied');?>\n".$str;
        return $str;
    }

    public function tpl_read($tplfile)
    {
        if ( !($fp= @fopen($tplfile,"r")))
        {
            exit( "温馨提示：不能打开tpl文件，请检查该文件是否存在并拥有读取权限" );
        }
        $str = fread($fp, filesize($tplfile) );
        fclose($fp);
        return $str;
    }

    public function tpl_write( $compiledtplfile, $str)
    {
        if (!($fp= @fopen($compiledtplfile, "w")))
        {
            exit( "温馨提示：不能打开tpl文件，请检查该文件是否存在并拥有读取权限" );
        }
        flock($fp,3 );
        if (!@fwrite($fp,$str))
        {
            exit("温馨提示：不能写入tpl文件，请检查该文件是否存在并拥有写入权限");
        }
        fclose($fp);
        return true;
    }

}

?>